document.addEventListener('DOMContentLoaded', async () => {
  const savedConfig = await getStoredConfig();
  // 默认配置项
  const defaultConfig = {
    selectorName: '.article-content img',
    fileName: '{NO}_{PAGE_TITLE}_{NAME}.{EXT}',
    downloadMode: '单图',
    viewType: '宫格',
    imageSorting: '原网排序',
  };
  const vm = new Vue({
    el: '#app',
    data: {
      configModel: { ...defaultConfig, ...(savedConfig || {}) },
      downloadModeArr: ['打包', '单图'],
      viewTypeArr: ['列表', '宫格'],
      imageSortingArr: ['原网排序', '大图优先', '小图优先'],
      btnArr: [
        { label: '保存设置', type: 'success' },
        { label: '还原设置', type: 'warning' },
        { label: '加载图片', type: 'primary' },
        { label: '下载图片', type: 'info' },
        { label: '在当前页面中下载', type: 'danger' },
      ],
      imageArr: [],
      btnDisabled: false,
      loading: false,
    },
    mounted() {
      // 监听 content-script.js 发送过来的数据
      chrome.runtime.onMessage.addListener(async response => {
        if (response.action == 'savedImages') {
          vm.$message.info(`${response.message}图片个数：${response.length}`);
          vm.btnDisabled = !response.length;
          return;
        }
        if (response.action == 'sendImages') {
          vm.loading = true;
          const images = await getImageArr(response.images);
          if (vm.configModel.downloadMode == '单图') {
            await Promise.all(images.map(async item => {
              return await downloadFile(item.src, item.fileName);
            }));
          } else {
            await packageDownload(images);
          }
          vm.loading = false;
        }
      });
    },
    methods: {
      async handleBtnClick(data) {
        if (data == '保存设置') {
          await setStored(CONFIG_KEY, this.configModel);
          vm.$message.success('保存设置成功');
          return;
        }
        if (data == '还原设置') {
          await setStored(CONFIG_KEY, defaultConfig);
          vm.$message.success('还原设置成功');
          return;
        }
        if (data == '加载图片') {
          const tabs = await tabsQuery();
          await setStored(PAGE_KEY, tabs[0]);
          chrome.runtime.sendMessage({
            action: 'collectImages',
            selectorName: vm.configModel.selectorName,
          });
          return;
        }
        if (data == '下载图片') {
          chrome.runtime.sendMessage({
            // action: 'db_getImages',
            action: 'dl_getImages',
            selectorName: vm.configModel.selectorName,
          });
          return;
        }
        if (data == '在当前页面中下载') {
          chrome.runtime.sendMessage({ action: 'dl_currPage', });
        }
      },
    },
  });
});
